package com.nettywork.code;

import com.entity.User;
import com.sun.org.apache.xpath.internal.operations.String;
import com.util.ProtostuffUtil;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

public class NettyClientHandler extends ChannelInboundHandlerAdapter {

    /**
     * 当客户端连接服务器完成的时候会调用该方法
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx){
        //这里如果写入对象大于2048个字节 那么 服务端解析的时候由于
        //byteBuf一次最大只能传送2048个字节 所以对象没有接收完
        //那么服务端反序列化的时候 就会报错。所以这里得拆包
        byte[] b = new byte[2000];
        User user = new User(1,"lvchao","13720169050");
        user.setB(b);
        ByteBuf byteBuf = Unpooled.copiedBuffer(ProtostuffUtil.serialize(user));
        ctx.writeAndFlush(byteBuf);
        System.out.println("发送数据成功");
    }

    /**
     * 读取服务端发送的数据
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
//        ByteBuf byteBuf = (ByteBuf)msg;
//        byte[] b = new byte[byteBuf.readableBytes()];
//        byteBuf.readBytes(b);
//        System.out.println(new String(b, CharsetUtil.UTF_8));
//        System.out.println(msg);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
